package com.hqyj.hrms.config.shiro;

import com.hqyj.hrms.modules.account.entity.Role;
import com.hqyj.hrms.modules.account.entity.User;
import com.hqyj.hrms.modules.account.service.RoleService;
import com.hqyj.hrms.modules.account.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class MyRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();

        User user = (User) principals.getPrimaryPrincipal();
        if (user == null) {
            throw new UnknownAccountException("This user name do not exist.");
        }

        List<Role> roles = new ArrayList<Role>();
        if (user.getUserName().equals("admin")) {
            roles = roleService.getRoles();
            if (roles.isEmpty()) {
                simpleAuthorizationInfo.addRole("admin");
            }
        } else {
            roles = roleService.getRolesByUserId(user.getUserId());
        }
        for (Role role : roles) {
            simpleAuthorizationInfo.addRole(role.getRoleName());
            /*List<Resource> resources = resourceService.getResourcesByRoleId(role.getRoleId());
            for (Resource resource : resources) {
                simpleAuthorizationInfo.addStringPermission(resource.getPermission());
            }*/
        }
        return simpleAuthorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String userName = (String) token.getPrincipal();
        User user = userService.getUserByUserName(userName);
        if (user == null) {
            throw new UnknownAccountException("This user name do not exist.");
        }

        // 身份验证器，包装用户名和密码
        return new SimpleAuthenticationInfo(user, user.getUserPwd(), getName());
    }

}
